package com.xxxx.server.config.security.compoent;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xxxx.server.pojo.RespBean;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
// AuthorizationEntryPoint授权点
// 当未登录或者token失效 访问接口时自定义的返回结果
public class RestAuthorizationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                         AuthenticationException e) throws IOException, ServletException {
        // 通过httpServletResponse去设置一些东西
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json");
        // out对象用于输出字符流数据
        PrintWriter out = httpServletResponse.getWriter();
        // 因为现在的状态的未登录/token失效
        RespBean bean = RespBean.error("RestAuthorizationEntryPoint 用户未登录或者token失效");
        bean.setCode(401);
        // 输出
        out.write(new ObjectMapper().writeValueAsString(bean));
        out.flush();
        out.close();
    }
}
